#include <iostream>
#include <Windows.h>

int main(int argc, char **argv)
{
	DWORD scManagerAccessRights = SC_MANAGER_CREATE_SERVICE;
	// http://msdn.microsoft.com/en-us/library/windows/desktop/ms684323%28v=vs.85%29.aspx
	SC_HANDLE scManager = OpenSCManager(NULL, NULL, scManagerAccessRights);

	if (!scManager)
	{
		std::cerr << "Error: Can't open Service Control Manager" << std::endl;
		return 1;
	}

	LPCTSTR serviceName = "KEXCB";
	LPCTSTR serviceDisplayName = "Kernel Exchange Buffer driver";
	LPCTSTR serviceBinaryFilename = argv[1];
	SC_HANDLE scService = NULL;
	// http://msdn.microsoft.com/en-us/library/windows/desktop/ms682450%28v=vs.85%29.aspx
	scService = CreateService(scManager,
							serviceName, serviceDisplayName,
							SERVICE_START | DELETE | SERVICE_STOP,
							SERVICE_KERNEL_DRIVER,
							SERVICE_DEMAND_START,
							SERVICE_ERROR_IGNORE,
							serviceBinaryFilename,
							NULL, NULL, NULL, NULL, NULL);
	if (!scService)
	{
		std::cerr << "Error: Can't create service" << std::endl;
		CloseServiceHandle(scManager);
		return 2;
	}

	// http://msdn.microsoft.com/en-us/library/windows/desktop/ms686321%28v=vs.85%29.aspx
	if (!StartService(scService, 0, NULL))
	{
		std::cerr << "Error: Can't start service" << std::endl;
		CloseServiceHandle(scManager);
		DeleteService(scService);
		CloseServiceHandle(scService);
		return 3;
	}

	std::cout << "Running..." << std::endl;
	getchar();

	SERVICE_STATUS serviceStatus;
	// http://msdn.microsoft.com/en-us/library/windows/desktop/ms682108%28v=vs.85%29.aspx
	if (!ControlService(scService, SERVICE_CONTROL_STOP, &serviceStatus))
	{
		std::cerr << "Error: Can't stop service" << std::endl;
		DeleteService(scService);
		CloseServiceHandle(scService);
		CloseServiceHandle(scManager);
		return 4;
	}

	if (!DeleteService(scService))
	{
		std::cerr << "Error: Can't delete service" << std::endl;
		CloseServiceHandle(scService);
		return 5;
	}

	if (!CloseServiceHandle(scService))
	{
		std::cerr << "Error: Can't close service handle" << std::endl;
		CloseServiceHandle(scManager);
		return 6;
	}

	// http://msdn.microsoft.com/en-us/library/windows/desktop/ms682028%28v=vs.85%29.aspx
	if (!CloseServiceHandle(scManager))
	{
		std::cerr << "Error: Can't close service manager handle" << std::endl;
		return 7;
	}

	return 0;
}
